package my.ts.code;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import my.ts.code.listener.ConfirmListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MusicPlayer extends BaseActivity implements OnBufferingUpdateListener,
		OnPreparedListener, OnCompletionListener, OnErrorListener, ConfirmListener {
	private int volume, percentDownloaded;
	ProgressDialog dialog;
	static final int PROGRESS_DIALOG = 0;

	private SeekBar seekbar;
	private SeekBar progressbar;
	private ImageButton pre;
	private ImageButton stop;
	private ImageButton play;
	private ImageButton next;
	private ImageView img;
	private boolean pausing = true;
	private boolean canRun = true;
	private boolean stopped = true, escape = false;
	private boolean isPlaying = false;
	AudioManager am;
	private TextView preSong;
	private TextView playingSong;
	private TextView nextSong;
	MediaPlayer mp;
	Thread progress;
	// private Content content;
	ArrayList<String> listSong = new ArrayList<String>();
	ArrayList<String> listLink = new ArrayList<String>();
	ArrayList<String> listDownload = new ArrayList<String>();

	private int currentSong;
	// , contentLength = 0, currentDownloaded = 0;
	private String avatar;
	// , result;
	private boolean canNext = true;
	private Button download;
	private Context context;
	private int id;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.music_player);
		context = this;
		setCListener(this);

		Bundle bundle = this.getIntent().getExtras();

		currentSong = bundle.getInt("position");
		listSong = bundle.getStringArrayList("title");
		listLink = bundle.getStringArrayList("link");
		listDownload = bundle.getStringArrayList("download");
		id = bundle.getInt("id");

		preSong = (TextView) findViewById(R.id.preSong);
		playingSong = (TextView) findViewById(R.id.playingSong);
		nextSong = (TextView) findViewById(R.id.nextSong);

		if (currentSong > 0)
			preSong.setText(listSong.get(currentSong - 1));
		playingSong.setText(listSong.get(currentSong));

		if (currentSong < listSong.size() - 1)
			nextSong.setText(listSong.get(currentSong + 1));

		img = (ImageView) findViewById(R.id.img);

		seekbar = (SeekBar) findViewById(R.id.progress);
		seekbar.setThumbOffset(0);
		progressbar = (SeekBar) findViewById(R.id.progressBar);
		progressbar.setThumbOffset(0);
		play = (ImageButton) findViewById(R.id.play);
		play.setImageResource(R.drawable.media_play);
		stop = (ImageButton) findViewById(R.id.stop);
		pre = (ImageButton) findViewById(R.id.pre);
		next = (ImageButton) findViewById(R.id.next);
		am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		volume = am.getStreamVolume(3);
		seekbar.setMax(am.getStreamMaxVolume(3));
		seekbar.setProgress(volume);
		seekbar.setOnSeekBarChangeListener(VolumeChange);

		progressbar.setOnSeekBarChangeListener(Loaded);

		play.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN: {
					if (pausing == true || stopped == true)
						play.setImageResource(R.drawable.media_play_hover);
					else
						play.setImageResource(R.drawable.media_pause_hover);
					break;
				}
				case MotionEvent.ACTION_UP: {
					if (isPlaying == false && pausing == false) {
						playSong(currentSong);
						break;
					}
					if (isPlaying == true && pausing == false) {
						pausing = true;
						mp.pause();
						play.setImageResource(R.drawable.media_play);
						break;
					}
					if (pausing == true && isPlaying == true) {
						// int index = progressbar.getProgress();
						canRun = false;
						mp.start();
						progress = new Thread() {
							@Override
							public void run() {
								int CurrentPosition = 0;
								int d = mp.getDuration();
								try {
									Thread.sleep(200);
								} catch (InterruptedException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
								canRun = true;
								pausing = false;
								while (canRun == true) {
									try {
										Thread.sleep(100);
										if (canRun == false)
											break;
										if (d != 0)
											CurrentPosition = (mp
													.getCurrentPosition() * 100)
													/ d;
										else
											CurrentPosition = 0;

									} catch (Exception e) {
									}
									progressbar.setProgress(CurrentPosition);
									progressbar
											.setSecondaryProgress(percentDownloaded);
								}
								if (stopped == true) {
									progressbar.setProgress(0);
									progressbar.setSecondaryProgress(0);
								}
							}
						};
						progress.start();

						pausing = false;
						play.setImageResource(R.drawable.media_pause);
						break;
					}
				}
					break;
				}
				return false;
			}
		});

		stop.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN: {
					stop.setImageResource(R.drawable.media_stop_hover);
					break;
				}
				case MotionEvent.ACTION_UP: {
					stop.setImageResource(R.drawable.media_stop);
					if (isPlaying == true) {
						mp.stop();
						mp.release();
						stopped = true;
						isPlaying = false;
						canRun = false;
						pausing = false;
						progressbar.setProgress(0);
						play.setImageResource(R.drawable.media_play);
					}
					break;
				}
				}
				return false;
			}
		});

		pre.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN: {
					pre.setImageResource(R.drawable.media_pre_hover);
					break;
				}
				case MotionEvent.ACTION_UP: {
					pre.setImageResource(R.drawable.media_pre);
					if ((currentSong > 0 && isPlaying == true)
							|| (stopped == true)) {
						canRun = false;
						if (isPlaying == true) {
							mp.stop();
							mp.release();
						}
						isPlaying = false;
						playSong(currentSong - 1);
					}
					break;
				}
				}
				return false;
			}
		});

		next.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN: {
					next.setImageResource(R.drawable.media_next_hover);
					break;
				}
				case MotionEvent.ACTION_UP: {
					next.setImageResource(R.drawable.media_next);
					if ((currentSong < listSong.size() - 1 && isPlaying == true)
							|| (stopped == true)) {
						canRun = false;
						if (isPlaying == true) {
							mp.stop();
							mp.release();
						}
						isPlaying = false;
						playSong(currentSong + 1);
					}
					break;
				}
				}
				return false;
			}
		});

		download = (Button) findViewById(R.id.download);
		download.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (id) {
				case Config.MUSIC:
					showDialogSelectSms(context, MusicPlayer.this, "Tùy chọn",
							"Bạn có đồng ý nhắn tin để $$$ clip", " clip",
							Config.MUSIC_SYNTAX.getSyntax()
									+ listDownload.get(currentSong),
							Config.MUSIC_SYNTAX.getNumber());
					
					break;

				case Config.AUDIO:
					showDialogSelectSms(context, MusicPlayer.this, "Tùy chọn",
							"Bạn có đồng ý nhắn tin để $$$ audio", " audio",
							Config.AUDIO_SYNTAX.getSyntax()
									+ listDownload.get(currentSong),
							Config.AUDIO_SYNTAX.getNumber());
					
					break;

				default:
					break;
				}
	
			}
		});
	}

	/*
	 * ***********************************************************************************************************************
	 */
	
	
	@Override
	public void onResume() {
		escape = false;
		super.onResume();
	}

	@Override
	public void onStart() {
		if (mp == null)
			playSong(currentSong);
		super.onStart();
	}

	/*
	 * ***********************************************************************************************************************
	 */

	@Override
	public void onBufferingUpdate(final MediaPlayer mp, int percent) {
		percentDownloaded = percent;
		// TODO Auto-generated method stub
	}

	/*
	 * ***********************************************************************************************************************
	 */

	@Override
	protected void onPause() {
		super.onPause();
	}

	/*
	 * ***********************************************************************************************************************
	 */

	private void releaseMediaPlayer() {
		if (mp != null) {
			mp.release();
			mp = null;
		}
	}

	/*
	 * ***********************************************************************************************************************
	 */

	private void playSong(final int pos) {
		if (isPlaying == true)
			mp.release();
		mp = new MediaPlayer();

		if ((pos < listLink.size()) && (pos >= 0)) {
			currentSong = pos;
			canNext = false;
//			showProgressDialog();

			final Handler mHandler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					if (escape == false)
						if (msg.what == 1) {
							canNext = true;
							AlertDialog.Builder builder = new AlertDialog.Builder(
									MusicPlayer.this);
							builder.setTitle("Thông báo");
							builder.setMessage("Giao dịch không thành công");
							builder.setPositiveButton("Đóng cửa sổ",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											// escape = true;
											// finish();
										}
									});
							builder.show();
							isPlaying = false;
							pausing = false;
							play.setImageResource(R.drawable.media_play);
						}
					super.handleMessage(msg);
				}
			};

			final Handler handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					if (escape == false) {
						if (msg.what == 1) {

							if (pos == 0) {
								preSong.setText("");
								playingSong.setText(listSong.get(pos));
								if (listLink.size() > 1)
									nextSong.setText(listSong.get(pos + 1));
							}
							if (pos == listLink.size() - 1) {
								if (listLink.size() > 1)
									preSong.setText(listSong.get(pos - 1));
								playingSong.setText(listSong.get(pos));
								nextSong.setText("");
							}
							if ((pos > 0) && (pos < listLink.size() - 1)) {
								if (listLink.size() > 1)
									preSong.setText(listSong.get(pos - 1));
								playingSong.setText(listSong.get(pos));
								if (listLink.size() > 1)
									nextSong.setText(listSong.get(pos + 1));
							}
							play.setImageResource(R.drawable.media_pause);

							System.out.println("DOWN="
									+ listDownload.get(currentSong));

							if (listDownload.get(currentSong) != null) {
								if (listDownload.get(currentSong).equals(""))
									download.setVisibility(View.GONE);
								else
									download.setVisibility(View.VISIBLE);
							} else
								download.setVisibility(View.GONE);
						}
					}
					super.handleMessage(msg);
				}
			};

			Thread thread = new Thread() {
				@Override
				public void run() {
					Message msg = handler.obtainMessage(1);
					handler.sendMessage(msg);
							try {
								System.out.println("PLAY:"+listLink.get(pos));
								mp.setDataSource(listLink.get(pos));
								mp.prepare();

							} catch (Exception e) {
								e.printStackTrace();
								canNext = true;
							}
				}
			};
			thread.start();
			mp.setOnBufferingUpdateListener(this);
			mp.setOnErrorListener(this);
			mp.setOnPreparedListener(this);
			mp.setOnCompletionListener(this);
		}
	}

	/*
	 * ***********************************************************************************************************************
	 */

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		canNext = true;
		canRun = false;
		escape = true;
		Log.i("tag", "msg escape");
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			canRun = false;
			if (mp != null)
				mp.release();
			finish();
			return false;
		}
		if (keyCode == KeyEvent.KEYCODE_ENDCALL) {
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	/*
	 * ***********************************************************************************************************************
	 */

	private OnSeekBarChangeListener VolumeChange = new OnSeekBarChangeListener() {
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			int index = seekbar.getProgress();
			am.setStreamVolume(3, index, 1);
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
		}
	};

	/*
	 * ***********************************************************************************************************************
	 */

	private OnSeekBarChangeListener Loaded = new OnSeekBarChangeListener() {
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			mp.pause();
			canRun = false;
			pausing = true;
			isPlaying = false;
		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			int index = progressbar.getProgress();
			int total = mp.getDuration();
			mp.seekTo((index * total / 100));
			mp.start();
			progress = new Thread() {
				@Override
				public void run() {
					int CurrentPosition = 0;
					int d = mp.getDuration();
					canRun = true;
					pausing = false;
					isPlaying = true;

					while (canRun == true) {
						try {
							Thread.sleep(100);
							if (canRun == false)
								break;
							if (d != 0)
								CurrentPosition = (mp.getCurrentPosition() * 100)
										/ d;
							else
								CurrentPosition = 0;

						} catch (Exception e) {
						}
						progressbar.setProgress(CurrentPosition);
						progressbar.setSecondaryProgress(percentDownloaded);
					}
					if (stopped == true) {
						progressbar.setProgress(0);
						progressbar.setSecondaryProgress(0);
					}
				}
			};
			progress.start();
		}
	};

	/*
	 * ***********************************************************************************************************************
	 */

	@Override
	public void onPrepared(final MediaPlayer mp) {
		// TODO Auto-generated method stub
		Log.i("tag", "msg prepared");
		if (isPlaying == false && escape == false) {
			canNext = true;
			mp.setOnPreparedListener(this);
			mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mp.start();
			stopped = false;
			pausing = false;
			isPlaying = true;
			progressbar.setMax(100);
			progressbar.setVisibility(View.VISIBLE);
			progressbar.setProgress(0);
			progressbar.setSecondaryProgress(0);
			Thread p = new Thread() {
				@Override
				public void run() {
					int CurrentPosition = 0;
					int d = mp.getDuration();
					canRun = true;
					while (canRun == true) {
						try {
							if (canRun == false)
								break;
							if (d != 0)
								CurrentPosition = (mp.getCurrentPosition() * 100)
										/ d;
							else
								CurrentPosition = 0;

						} catch (Exception e) {
						}
						progressbar.setProgress(CurrentPosition);
						progressbar.setSecondaryProgress(percentDownloaded);
					}
					if (stopped == true) {
						progressbar.setProgress(0);
						progressbar.setSecondaryProgress(0);
					}

				}
			};
			p.start();
		} else if (escape == true)
			mp.release();
	}

	/*
	 * ***********************************************************************************************************************
	 */

	protected void showProgressDialog() {
		if (dialog == null) {
			dialog = ProgressDialog.show(MusicPlayer.this, "", "Buffering...",
					true, true);
			Thread progress = new Thread() {
				@Override
				public void run() {
					while (canNext == false) {
					}

					if (canNext == true) {
						dialog.dismiss();
					}
				}
			};
			progress.start();
		} else if (!dialog.isShowing()) {
			dialog = ProgressDialog.show(MusicPlayer.this, "", "Buffering...",
					true, true);
			Thread progress = new Thread() {
				@Override
				public void run() {
					while (canNext == false) {
					}

					if (canNext == true) {
						dialog.dismiss();
					}
				}
			};
			progress.start();
		}
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub
		Log.i("tag", "msg completion");
		mp.stop();
		mp.release();
		canNext = false;
		pausing = true;
		canRun = false;
		stopped = true;
		isPlaying = false;
		play.setImageResource(R.drawable.media_play);
		// try {
		// Thread.sleep(500);
		// } catch (InterruptedException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// playSong(currentSong + 1);

	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		// TODO Auto-generated method stub
		Log.i("tag", "msg ------------- on Error " + what + "  extra = "
				+ extra);
		play.setImageResource(R.drawable.media_play);
		pausing = true;
		canRun = false;
		stopped = true;
		isPlaying = false;
		canNext = false;
		return false;
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		Log.i("tag", "msg here...............");
		if (event.getKeyCode() != 82 && event.getKeyCode() != 24
				&& event.getKeyCode() != 25) {
			canNext = true;
			if (mp != null)
				mp.release();
			pausing = true;
			play.setImageResource(R.drawable.media_play);
			if (KeyEvent.KEYCODE_BACK == event.getKeyCode()
					&& event.getAction() == KeyEvent.ACTION_DOWN) {
				escape = true;
				if (mp != null)
					mp.release();
				finish();
			}
		}
		return false;
	}

	@Override
	public void confirmListener(boolean done) {
		// TODO Auto-generated method stub
		
	}


}
